package cn.ld.fj.web.food;

import cn.ld.fj.dao.HibernateUtils;
import cn.ld.fj.entity.Food;
import cn.ld.fj.entity.FoodType;
import cn.ld.fj.entity.account.Role;
import cn.ld.fj.entity.account.User;
import cn.ld.fj.pojo.FoodTypePojo;
import cn.ld.fj.pojo.TreePojo;
import cn.ld.fj.service.account.AccountManager;
import cn.ld.fj.service.food.FoodManager;
import cn.ld.fj.service.food.FoodTypeManager;
import cn.ld.fj.service.log.OperationLogManager;
import cn.ld.fj.util.DwzUtil;
import cn.ld.fj.web.JsonActionSupport;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.esoar.modules.orm.Page;
import net.esoar.modules.orm.PropertyFilter;
import net.esoar.modules.utils.encode.JsonBinder;
import net.esoar.modules.utils.web.struts2.Struts2Utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户管理Action.
 * <p/>
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 *
 * @author fly
 */
// 定义URL映射对应/account/user.action
@Namespace("/foodType")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({@Result(name = JsonActionSupport.RELOAD, location = "food-type.action", type = "redirect")})
public class FoodTypeAction extends JsonActionSupport<FoodType> {


    @Autowired
    private FoodTypeManager foodTypeManager;
    @Autowired
    private OperationLogManager operationLogManager;
    @Autowired
    private FoodManager foodManager;

    private Long id;
    private FoodType entity;
    private Page<FoodType> page = new Page<FoodType>(10);// 每页5条记录


    private List<FoodTypePojo> foodTypePojos = Lists.newArrayList();

    public List<FoodTypePojo> getFoodTypePojos() {
        return foodTypePojos;
    }

    public void setFoodTypePojos(List<FoodTypePojo> foodTypePojos) {
        this.foodTypePojos = foodTypePojos;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public FoodType getModel() {
        return entity;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = foodTypeManager.getOne(id);
        } else {
            entity = new FoodType();
        }
    }

    // -- CRUD Action 函数 --//
    @Override
    public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter
                .buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }

        page = foodTypeManager.getPage(page, filters);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            for (FoodType foodType : page.getResult()) {
                foodType.setLevel(1);
                if (foodType.getPid() > 0) {
                    FoodType pfood = foodTypeManager.getOne(foodType.getPid());
                    foodType.setPname(pfood.getName());
                    foodType.setLevel(2);
                    if (pfood.getPid() > 0) {
                        FoodType food = foodTypeManager.getOne(pfood.getPid());
                        foodType.setPname(foodType.getPname() + "->" + food.getName());
                        foodType.setLevel(3);
                    }

                }
            }
        }


        return SUCCESS;
    }

    @Override
    public String input() throws Exception {

        List<FoodType> foodTypes = foodTypeManager.getFirstLevel();
        if (CollectionUtils.isNotEmpty(foodTypes)) {
            for (FoodType foodType : foodTypes) {
                FoodTypePojo foodTypePojo = new FoodTypePojo();
                foodTypePojo.setId(foodType.getId());
                foodTypePojo.setName(foodType.getName());

                List<FoodType> seconds = foodTypeManager.getSecondFoodTypes(foodType.getId());
                if (CollectionUtils.isNotEmpty(seconds)) {
                    for (FoodType secondFoodType : seconds) {
                        FoodTypePojo secondPojo = new FoodTypePojo();
                        BeanUtils.copyProperties(secondFoodType, secondPojo);
                        foodTypePojo.getFoodTypePojoList().add(secondPojo);

                    }
                }
                foodTypePojos.add(foodTypePojo);
            }
        }

        return INPUT;
    }


    public void trees() {

        List<TreePojo> treePojos = Lists.newArrayList();

        List<FoodType> foodTypes = foodTypeManager.getFirstLevel();
        if (CollectionUtils.isNotEmpty(foodTypes)) {
            for (FoodType foodType : foodTypes) {
                TreePojo foodTypePojo = new TreePojo();
                BeanUtils.copyProperties(foodType, foodTypePojo);
                foodTypePojo.setOpen(true);

                foodTypePojo.setOrderRefer(foodManager.getFood(foodType.getId()));

                List<FoodType> seconds = foodTypeManager.getSecondFoodTypes(foodType.getId());
                if (CollectionUtils.isNotEmpty(seconds)) {
                    for (FoodType second : seconds) {
                        TreePojo secondPojo = new TreePojo();
                        BeanUtils.copyProperties(second, secondPojo);
                        secondPojo.setOpen(true);
                        secondPojo.setOrderRefer(foodManager.getFood(second.getId()));

                        List<FoodType> thirds = foodTypeManager.getSecondFoodTypes(second.getId());
                        if (CollectionUtils.isNotEmpty(thirds)) {
                            for (FoodType third : thirds) {
                                TreePojo thirdPojo = new TreePojo();
                                BeanUtils.copyProperties(third, thirdPojo);
                                secondPojo.getChildren().add(thirdPojo);
                                thirdPojo.setOrderRefer(foodManager.getFood(third.getId()));
                                if (thirdPojo.isOrderRefer()) {
                                    secondPojo.setOrderRefer(true);
                                }
                            }
                        }

                        if (secondPojo.isOrderRefer()) {
                            foodTypePojo.setOrderRefer(true);
                        }

                        foodTypePojo.getChildren().add(secondPojo);
                    }

                }

                treePojos.add(foodTypePojo);
            }
        }
        try {
            Struts2Utils.getResponse().getWriter().print(JsonBinder.buildNormalBinder().toJson(treePojos));
            Struts2Utils.getResponse().getWriter().flush();

            System.out.println(JsonBinder.buildNormalBinder().toJson(treePojos));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void treeSubmit() {
        HttpServletRequest request = Struts2Utils.getRequest();


        HttpServletResponse response = Struts2Utils.getResponse();
        String data = request.getParameter("data");
        System.out.println(data);

        List<TreePojo> treePojos = JSON.parseArray(data, TreePojo.class);

        Map<Long, Long> map = Maps.newHashMap();

        if (CollectionUtils.isNotEmpty(treePojos)) {
            for (TreePojo treePojo : treePojos) {
                if (treePojo.getId() == null) {
                    //新增的
                    FoodType foodType = new FoodType();
                    foodType.setName(treePojo.getName());
                    foodType.setPid(0L);
                    foodTypeManager.save(foodType);
                    map.put(foodType.getId(), foodType.getId());

                    if (CollectionUtils.isNotEmpty(treePojo.getChildren())) {
                        for (TreePojo second : treePojo.getChildren()) {
                            FoodType secondType = new FoodType();
                            secondType.setName(second.getName());
                            secondType.setPid(foodType.getId());
                            foodTypeManager.save(secondType);
                            map.put(secondType.getId(), secondType.getId());


                            if (CollectionUtils.isNotEmpty(second.getChildren())) {
                                for (TreePojo third : second.getChildren()) {
                                    FoodType thirdType = new FoodType();
                                    thirdType.setName(third.getName());
                                    thirdType.setPid(secondType.getId());
                                    foodTypeManager.save(thirdType);
                                    map.put(thirdType.getId(), thirdType.getId());

                                }

                            }

                        }

                    }


                } else {
                    //修改
                    FoodType foodType = new FoodType();
                    foodType.setName(treePojo.getName());
                    foodType.setId(treePojo.getId());
                    foodType.setPid(0L);
                    foodTypeManager.save(foodType);

                    map.put(treePojo.getId(), treePojo.getId());

                    if (CollectionUtils.isNotEmpty(treePojo.getChildren())) {
                        for (TreePojo second : treePojo.getChildren()) {
                            FoodType secondType = new FoodType();
                            secondType.setName(second.getName());
                            secondType.setPid(foodType.getId());
                            if (second.getId() != null) {
                                secondType.setId(second.getId());
                                map.put(second.getId(), second.getId());
                            }

                            foodTypeManager.save(secondType);

                            if (CollectionUtils.isNotEmpty(second.getChildren())) {
                                for (TreePojo third : second.getChildren()) {
                                    FoodType thirdType = new FoodType();
                                    thirdType.setName(third.getName());
                                    thirdType.setPid(secondType.getId());
                                    if (third.getId() != null) {
                                        thirdType.setId(third.getId());
                                        map.put(third.getId(), third.getId());
                                    }

                                    foodTypeManager.save(thirdType);

                                }

                            }

                        }


                    }


                }
            }
            List<FoodType> foodTypes = foodTypeManager.getAll();

//            //如果删除了的话
            if (CollectionUtils.isNotEmpty(foodTypes)) {
                for (FoodType foodType1 : foodTypes) {
                    if (!map.containsKey(foodType1.getId())) {
                        foodTypeManager.delete(foodType1.getId());
                    }
                }
            }

        }


        try {
            response.getWriter().print("ok");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void save() throws Exception {

        foodTypeManager.save(entity);
        operationLogManager.saveLog("增加/修改菜品分类信息");

        Struts2Utils.renderHtml(DwzUtil.getCloseCurrentReturn("w_foodType",
                "操作成功"));
    }

    @Override
    public void delete() throws Exception {


        List<FoodType> foodTypes = foodTypeManager.getSecondFoodTypes(id);
        if (CollectionUtils.isNotEmpty(foodTypes)) {
            Struts2Utils.renderHtml(DwzUtil.getFailReturn("该菜单存在子类，不能删除"));
            return;


        }
        try {
            foodTypeManager.delete(id);
            operationLogManager.saveLog("删除菜品分类信息");

        } catch (Exception e) {
            return;
        }

        Struts2Utils.renderHtml(DwzUtil.getNavtabReturn("w_foodType",
                "操作成功"));
    }


    public Long getId() {
        return id;
    }

    public FoodType getEntity() {
        return entity;
    }

    public void setEntity(FoodType entity) {
        this.entity = entity;
    }

    public Page<FoodType> getPage() {
        return page;
    }

    public void setPage(Page<FoodType> page) {
        this.page = page;
    }
}
